import GameArea from "./gameArea.js";
import GamePiece from "./gamePiece.js";
import Sound from "./sound.js";

let myGameArea,
  myGamePiece,
  myScore,
  mySound,
  myMusic,
  myObstacles = [],
  interval;
function startGame() {
  myGameArea = new GameArea();
  myGamePiece = new GamePiece(
    30,
    30,
    "red",
    10,
    120,
    myGameArea.context,
    "rectangle"
  );
  myScore = new GamePiece(
    "30px",
    "Consolas",
    "black",
    280,
    40,
    myGameArea.context,
    "text"
  );
  mySound = new Sound("bounce.mp3");
  myMusic = new Sound("bg.mp3");

  window.addEventListener("click", () => {
    myMusic?.play();
  });
  // 480 262 10 218
  // 设置定时器 0.02s 更新布局
  interval = setInterval(updateGameArea, 20);
}

function everyinterval(n) {
  if ((myGameArea.frameNo / n) % 1 == 0) {
    return true;
  }
  return false;
}

function updateGameArea() {
  // 判断是否碰
  const crash = myObstacles.some((obstacle) =>
    myGamePiece.crashWidth(obstacle)
  );
  if (crash) {
    mySound.play();
    myMusic.stop();
    myMusic = null;
    clearInterval(interval);
  } else {
    // 清除画布
    myGameArea.clear();
    myGameArea.frameNo += 1;

    let x, height, gap, minHeight, maxHeight, minGap, maxGap;
    if (myGameArea.frameNo == 1 || everyinterval(150)) {
      x = myGameArea.canvas.width;
      minHeight = 20;
      maxHeight = 200;
      height = Math.floor(
        Math.random() * (maxHeight - minHeight + 1) + minHeight
      );
      minGap = 50;
      maxGap = 200;
      gap = Math.floor(Math.random() * (maxGap - minGap + 1) + minGap);

      myObstacles.push(
        new GamePiece(
          10,
          height,
          "yellowgreen",
          x,
          0,
          myGameArea.context,
          "line"
        ),
        new GamePiece(
          10,
          x - height - gap,
          "yellowgreen",
          x,
          height + gap,
          myGameArea.context,
          "line"
        )
      );
    }
    for (let i = 0; i < myObstacles.length; i++) {
      myObstacles[i].speedX = -1;
      myObstacles[i].newPos();
      myObstacles[i].update();
    }

    myScore.text = "分数：" + myGameArea.frameNo;
    myScore.update();

    myGamePiece.newPos();
    myGamePiece.update();
  }
}

function stopMove() {
  myGamePiece.speedX = 0;
  myGameArea.speedY = 0;
}

function accelerate(n) {
  myGamePiece.gravity = n;
  console.log(n);
}

// Add this in your index.js module
const boostButton = document.getElementsByTagName("button")[0];
// Add event listeners
boostButton.addEventListener("mousedown", () => accelerate(-0.2));
boostButton.addEventListener("mouseup", () => accelerate(0.1));

startGame();
